package com.ericsson.enap.modules.ebmLog.thread;

import com.ericsson.common.util.RedisCache;
import com.ericsson.common.util.SpringUtils;
import com.ericsson.enap.modules.ebmLog.entity.vgc.VgcNetEntity;
import com.ericsson.enap.modules.ebmLog.service.vgc.VgcEbmDownloadProcess;
import org.slf4j.Logger;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

public class VgcEbmDownloadProcessThread implements Runnable {
    private RedisCache redisCache;
    private VgcEbmDownloadProcess vgcEbmDownloadProcess;
    private VgcNetEntity vgcNetEntity;
    private String storePath;
    private String netType;
    private CountDownLatch latch;
    private String redisKey="vgc:ebm:download:";
    private Logger log;
    public VgcEbmDownloadProcessThread(VgcNetEntity vgcNetEntity, String storePath, String netType, CountDownLatch latch,Logger log,RedisCache redisCache) {
        this.redisCache=redisCache;
        this.vgcEbmDownloadProcess= SpringUtils.getBean("vgcEbmDownloadProcess" + netType + "Impl");
        this.vgcNetEntity=vgcNetEntity;
        this.storePath=storePath;
        this.netType=netType;
        this.log=log;
        this.latch=latch;
    }

    @Override
    public void run() {
        log.info("========= downLoadFiles netName:"+vgcNetEntity.getName()+" start=========");
        String ebmlogtime=redisCache.getCacheObject(redisKey+"ebmlogtime"+":"+vgcNetEntity.getId());
        boolean down=true;
        if(null==ebmlogtime||ebmlogtime.equals("")){
            down=false;
            ebmlogtime="0";
        }
        try {
            String downloadTime=vgcEbmDownloadProcess.downloadFile(vgcNetEntity,storePath,log,down,ebmlogtime);
            if(null!=downloadTime&&!downloadTime.equals("")){
                redisCache.setCacheObject(redisKey+"ebmlogtime"+":"+vgcNetEntity.getId(),downloadTime);
                redisCache.expire(redisKey+"ebmlogtime"+":"+vgcNetEntity.getId(),10, TimeUnit.HOURS);
            }
        } catch (Exception e) {
            log.info("==== VgcEbmDownloadProcessThread run exception: "+e);
        } finally {
            latch.countDown();
        }
        log.info("========= downLoadFiles netName:"+vgcNetEntity.getName()+" end=========");

    }
}
